﻿using Namotion.Reflection;

namespace Photo.Core.Extensions
{
    /// <summary>
    /// 列表扩展方法
    /// </summary>
    public static class ListExtension
    {
        /// <summary>
        /// 列表转Tree
        /// 使用反射进行转换，仅限小型列表数据使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="idFieldName">主键所属字段</param>
        /// <param name="pIdFieldName">parent关联字段</param>
        /// <param name="childFieldName">将要转换的子集列表字段</param>
        /// <param name="pIdValue">parent关联字段的值</param>
        /// <returns></returns>
        public static List<T> ToTree<T>(this List<T> list, string idFieldName, string pIdFieldName, string childFieldName, object pIdValue)
        {
            var treeList = new List<T>();

            if (list == null || list.Count == 0)
            {
                return treeList;
            }

            //先获取父级列表
            var parentList = list.FindAll(o => typeof(T).GetProperty(pIdFieldName).GetValue(o).Equals(pIdValue));
            foreach (var item in parentList)
            {
                var idValue = typeof(T).GetProperty(idFieldName).GetValue(item);
                var childList = list.ToTree(idFieldName, pIdFieldName, childFieldName, idValue);
                typeof(T).GetProperty(childFieldName).SetValue(item, childList);
                treeList.Add(item);
            }
            return treeList;
        }

        /// <summary>
        /// 扩展列表转字符串分割拼接
        /// </summary>
        /// <param name="list"></param>
        /// <param name="splitStr"></param>
        /// <returns></returns>
        public static string Join(this IEnumerable<string> list,string splitStr)
        {
            return string.Join(splitStr, list) ?? string.Empty;
        }
    }
}